from flask import Blueprint, jsonify, request
from app.err_no import errno_no
from loguru import logger
import json
import traceback
from app.db.mongoClient import MongoError
from app.db import dbDishManage

blueprint = Blueprint('dish_manage', __name__, url_prefix='/api/dish')


@blueprint.route('/v1/create_dishes', methods=['POST'])
def create_dishes():
    '''
    创建新菜品
    '''
    try:
        j_data = json.loads(request.data)
        diningNo = j_data.get('diningNo')
        stallNo = j_data.get('stallNo')
        dishName = j_data.get('dishName')
        dishPrice = j_data.get('dishPrice')
        dishUnit = j_data.get('dishUnit') # 可选字段
        dishDesc = j_data.get('dishDesc') # 可选字段
        classNames = j_data.get('classNames') # 可选字段 array[]
        menuNames = j_data.get('menuNames') # 可选字段 array[]
        imageSrc = j_data.get('imageSrc') 
        if diningNo is None or len(diningNo) <= 0 \
            or stallNo is None or len(stallNo) <= 0 \
            or dishName is None or len(stallNo) <= 0 \
            or dishPrice is None or isinstance(dishPrice, int) is False \
            or dishUnit is None \
            or dishDesc is None \
            or classNames is None \
            or menuNames is None or len(menuNames) < 1 \
            or imageSrc is None:
            return jsonify(errno_no.ErrServerParam.data(None))

        dishId = dbDishManage.createDish(diningNo, stallNo, dishName, dishPrice, 
                            dishUnit, classNames, menuNames, dishDesc, imageSrc)
        # 菜品已存在
        if dishId is False:
            return jsonify(errno_no.ErrDishNameCreateExist.data(None))

        return jsonify(errno_no.OK.data({'dishId': dishId}))
    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))


@blueprint.route('/v1/edit_dishes', methods=['POST'])
def edit_dishes():
    '''
    编辑菜品基本信息
    '''
    try:
        j_data = json.loads(request.data)
        diningNo = j_data.get('diningNo')
        stallNo = j_data.get('stallNo')
        dishId = j_data.get('dishId')
        dishName = j_data.get('dishName')
        dishPrice = j_data.get('dishPrice')
        dishUnit = j_data.get('dishUnit') # 可选字段
        dishDesc = j_data.get('dishDesc') # 可选字段
        classNames = j_data.get('classNames') # 可选字段 array[]
        menuNames = j_data.get('menuNames') # 可选字段 array[]
        imageSrc = j_data.get('imageSrc') 
        
        if diningNo is None or len(diningNo) <= 0 \
            or stallNo is None or len(stallNo) <= 0 \
            or dishId is None or len(dishId) <= 0 \
            or dishName is None or len(dishName) <= 0 \
            or dishPrice is None or isinstance(dishPrice, int) is False \
            or dishUnit is None \
            or dishDesc is None \
            or classNames is None \
            or menuNames is None or len(menuNames) < 1 \
            or imageSrc is None:
            return jsonify(errno_no.ErrServerParam.data(None))

        res = dbDishManage.editDish(diningNo, stallNo, dishId, dishName, 
                    dishPrice, dishUnit, classNames, menuNames, dishDesc, imageSrc)
        if res is False:
            return jsonify(errno_no.ErrDishNameEditExist.data(None))

        if res is None:
            return jsonify(errno_no.ErrServerDocumentNotExist.data(None))

        return jsonify(errno_no.OK.data(None))
    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))


@blueprint.route('/v1/del_dishes', methods=['POST'])
def del_dishes():
    '''
    删除指定菜品
    '''
    try:
        j_data = json.loads(request.data)
        diningNo = j_data.get('diningNo')
        stallNo = j_data.get('stallNo')
        dishId = j_data.get('dishId')
        if diningNo is None or len(diningNo) <= 0 \
            or stallNo is None or len(stallNo) <= 0 \
            or dishId is None or len(dishId) <= 0 :
            return jsonify(errno_no.ErrServerParam.data(None))

        res = dbDishManage.delDish(diningNo, stallNo, dishId)
        if res is None:
            return jsonify(errno_no.ErrServerDocumentNotExist.data(None))

        return jsonify(errno_no.OK.data(None))
    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))


@blueprint.route('/v1/sort_class', methods=['POST'])
def sort_class():
    '''
    调整档口菜品类别排序
    '''
    try:
        j_data = json.loads(request.data)
        diningNo = j_data.get('diningNo')
        stallNo = j_data.get('stallNo')
        classList = j_data.get('classList')
        if diningNo is None or len(diningNo) <= 0 \
            or stallNo is None or len(stallNo) <= 0 \
            or classList is None or len(classList) <= 0 :
            return jsonify(errno_no.ErrServerParam.data(None))

        # 判断classList数组里是否符合要求
        NameList = []
        bPass = True
        for v in classList:
            className = v.get('className')
            classSort = v.get('classSort')
            NameList.append(className)
            # isinstance 判断某个数是不是整数
            if className is None or len(className) <= 0 \
                or classSort is None or isinstance(classSort, int) is False :
                bPass = False
                break

        if bPass is False:
            return jsonify(errno_no.ErrServerParam.data(None))

        # 判断类别是不是有重名的
        if len(NameList) > 0 and len(set(NameList)) < len(NameList):
            return jsonify(errno_no.ErrServerDocumentExist.data(None))

        res = dbDishManage.sortClass(diningNo, stallNo, classList)
        if res is None:
            return jsonify(errno_no.ErrServerDocumentNotExist.data(None))

        return jsonify(errno_no.OK.data(None))
    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))


@blueprint.route('/v1/sort_dishes', methods=['POST'])
def sort_dishes():
    '''
    调整菜品排序
    '''
    try:
        j_data = json.loads(request.data)
        diningNo = j_data.get('diningNo')
        stallNo = j_data.get('stallNo')
        dishIds = j_data.get('dishIds')
        if diningNo is None or len(diningNo) <= 0 \
            or stallNo is None or len(stallNo) <= 0 \
            or dishIds is None or len(dishIds) <= 0 :
            return jsonify(errno_no.ErrServerParam.data(None))

        # 判断dishIds数组里是否符合要求
        bPass = True
        for v in dishIds:
            dishId = v.get('dishId')
            dishSort = v.get('dishSort')
            # isinstance 判断某个数是不是整数
            if dishId is None or len(dishId) <= 0 \
                or dishSort is None or isinstance(dishSort, int) is False :
                bPass = False
                break

        if bPass is False:
            return jsonify(errno_no.ErrServerParam.data(None))

        res = dbDishManage.sortDish(diningNo, stallNo, dishIds)
        if res is None:
            return jsonify(errno_no.ErrServerDocumentNotExist.data(None))

        return jsonify(errno_no.OK.data(None))
    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))


@blueprint.route('/v1/del_dishes_batch', methods=['POST'])
def del_dishes_batch():
    '''
    批量删除指定档口菜品
    '''
    try:
        j_data = json.loads(request.data)
        diningNo = j_data.get('diningNo')
        stallNo = j_data.get('stallNo')
        dishIds = j_data.get('dishIds')
        if diningNo is None or len(diningNo) <= 0 \
            or stallNo is None or len(stallNo) <= 0 \
            or dishIds is None or len(dishIds) <= 0 :
            return jsonify(errno_no.ErrServerParam.data(None))

        res = dbDishManage.delDishs(diningNo, stallNo, dishIds)
        if res is None:
            return jsonify(errno_no.ErrServerDocumentNotExist.data(None))

        return jsonify(errno_no.OK.data(None))
    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))


@blueprint.route('/v1/create_batch_dishes', methods=['POST'])
def create_batch_dishes():
    '''
    批量创建档口菜品
    '''
    try:
        j_data = json.loads(request.data)
        diningNo = j_data.get('diningNo')
        stallNo = j_data.get('stallNo')
        dishList = j_data.get('dishList') 
        if diningNo is None or len(diningNo) <= 0 \
            or stallNo is None or len(stallNo) <= 0 \
            or dishList is None or len(dishList) <= 0:
            return jsonify(errno_no.ErrServerParam.data(None))

        bPass = True
        for v in dishList:
            dishName = v.get('dishName')
            dishPrice = v.get('dishPrice')
            dishUnit = v.get('dishUnit') # 可选字段
            dishDesc = v.get('dishDesc') # 可选字段
            classNames = v.get('classNames') # 可选字段 array[]
            menuNames = v.get('menuNames') # 可选字段 array[]
            imageSrc = v.get('imageSrc') 

            if dishName is None or len(dishName) <= 0 \
                or dishPrice is None or isinstance(dishPrice, int) is False \
                or dishUnit is None \
                or dishDesc is None \
                or classNames is None \
                or menuNames is None or len(menuNames) < 1 \
                or imageSrc is None:

                bPass = False
                break

        if bPass is False:
            return jsonify(errno_no.ErrServerParam.data(None))


        dishData = dbDishManage.createBatchDish(diningNo, stallNo, dishList)
        # 菜品已存在
        if dishData is False:
            return jsonify(errno_no.ErrServerDocumentExist.data(None))

        return jsonify(errno_no.OK.data({"dishIdList": dishData}))
    except MongoError as e:
        logger.error(f'操作mongo异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))
    except Exception as e:
        logger.error(f'业务异常:{e.__dict__},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))